package com.example.health.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.health.common.Result;
import com.example.health.entity.User;
import com.example.health.entity.UserRole;
import com.example.health.enums.PwdEnum;
import com.example.health.enums.RoleEnum;
import com.example.health.mapper.RoleMapper;
import com.example.health.mapper.UserMapper;
import com.example.health.mapper.UserRoleMapper;
import com.example.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder; //注入bcryct加密

    @Override
    public Page<User> getPage(Integer pageNum, Integer pageSize, String search) {

        Page<User> userPage = userMapper.findPage(new Page<>(pageNum, pageSize), search);


        //遍历查询 userPage.getRecords 就是得到查询的数据
        for (User record : userPage.getRecords()) {
            //根据用户的id去查询对应的相关信息
            List<UserRole> roles = roleMapper.getUserRoleByUserId(record.getId());
//通过流的map映射只要对应的角色id
            List<Integer> roleIds = roles.stream().map(UserRole::getRoleId).distinct().collect(Collectors.toList());
            //把身份设置给用户的属性
            record.setRoles(roleIds);

        }

        return userPage;
    }

    @Override
    public Result<?> add(User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res != null) {
            return Result.error("-1", "用户名重复");
        }
        if (user.getPassword() == null) {
            user.setPassword(bCryptPasswordEncoder.encode(PwdEnum.PASSWORD.getPassword()));
        }
        //插入数据库
        userMapper.insert(user);
//  给一个userRole对象设置关于用户和角色的相关信息
        UserRole userRole = UserRole.builder().userId(user.getId()).roleId(RoleEnum.USER.getRoleId()).build();
        //让用户和角色之间建立连接
        userRoleMapper.insert(userRole);

        return Result.success();
    }

    @Override
    public User selectById(Long id) {
        User user=userMapper.selectById(id);
        return user;
    }
}
